package com.example.movie.controller;



import com.example.movie.MinioTemplate;
import com.example.movie.UtilConstant;
import com.example.movie.vo.RestResult;
import com.example.movie.vo.RestResultBuilder;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: TY
 * @Dscription:
 * @Date: Created in 9:01 2018/10/31
 * @Modified By:
 */
@RestController
@RequestMapping(value = "file")
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);
    private SimpleDateFormat dateFormat = new SimpleDateFormat(UtilConstant.FULL_DATE);

    @Autowired
    private MinioTemplate minioTemplate;



    /**
     * 图片上传接口
     *
     * @param request
     * @param response
     * @param file     上传的文件
     * @throws IOException
     */
    @RequestMapping(value = "imgUpload", method = RequestMethod.POST)
    public RestResult imgUpload(HttpServletRequest request, HttpServletResponse response,
                                MultipartFile file) throws IOException {
        response.setContentType(UtilConstant.CONTENT_TYPE);
        Map<String, Object> returnMap = new HashMap<>();
        System.out.println(file.getOriginalFilename());
        int code = 1;
        String path = null;
        //判断文件是否为空
        if (!file.isEmpty()) {
            UUID uuid = UUID.randomUUID();
            String s = uuid.toString();
            String replace = s.replace("-", "");
            String substring = replace.substring(0, 1);
            String substring1 = replace.substring(1, 2);

            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            path = "public/img/"+substring+"/"+substring1 +"/"+ replace+".jpg";
            try {
                minioTemplate.putObject(path, inputStream);
            } catch (Exception e) {
                e.printStackTrace();
            }
            code = 0;
            returnMap.put("code",code);
            returnMap.put("path",path);
            return new RestResultBuilder<>().success("查询成功", returnMap);
        } else {
            return new RestResultBuilder<>().success("文件为空");

        }
    }


}
